package com.apes.hr.recruit.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.recruit.model.ApplyJobOrder;
import com.apes.hr.recruit.model.EmployContract;
import com.apes.hr.recruit.repository.ApplyJobOrderRepository;
import com.apes.hr.recruit.repository.EmployContractRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能：聘用合同
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrEmployContractService")
public class EmployContractService extends DomainService {
    @Autowired
    public EmployContractRepository employContractRepository;
    @Autowired
    public ApplyJobOrderRepository applyJobOrderRepository;
    /***
     * 功能：创建
     * @param request
     * @return
     */
    public EmployContract create(SimpleRequest request) {
        EmployContract employContract = request.getO(EmployContract.class);
        //ESB-5765 合同创建后自动为审核状态
        employContract.setState("done");
        return employContractRepository.saveAndFlush(employContract);
    }



    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public EmployContract update(SimpleRequest request) {
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        EmployContract employContract = employContractRepository.findOne(id);
        if (employContract == null) throw new RuntimeException("聘用合同【" + id + "】在系统中不存在。");
        if(employContract.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
        EmployContract employContractData = request.getO(EmployContract.class);
        return employContractRepository.saveAndFlush(employContractData);
    }

    /***
     * 功能： 删除
     * @param request
     * @return
     * @throws Exception
     */
    public String delete(SimpleRequest request) throws Exception {
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        EmployContract employContract = employContractRepository.findOne(id);
        if (employContract == null) throw new RuntimeException("聘用合同【" + id + "】在系统中不存在。");
        if(employContract.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
        employContract.setState("delete");
        employContractRepository.saveAndFlush(employContract);
//        employContractRepository.delete(id);

        return "删除成功！";
    }

    /***
     * 功能： 审核
     * @param request
     * @return
     */
    public EmployContract done(SimpleRequest request) throws RuntimeException {
        String id = request.get("id");
        EmployContract employContract = employContractRepository.findOne(id);
        if (employContract == null) throw new RuntimeException("聘用合同【" + id + "】在系统中不存在。");
        // 入职更新 员工状态 已改到入职申请单 此处不应再控制
//        if(employContract.getEmployee().getEmployeeState().getId().equals("000088")){
//            throw new RuntimeException("不可重复入职!");
//        }
        //调用了的入职单做标记
        List<ApplyJobOrder> jobOrders = applyJobOrderRepository.findByEmployeeAndState(id,"done");
        if(jobOrders.size()>0){
             ApplyJobOrder applyJobOrder =jobOrders.get(0);
             applyJobOrder.setInvoking(true);
             applyJobOrderRepository.saveAndFlush(applyJobOrder);
        }
        employContract.setState("done");
        employContractRepository.saveAndFlush(employContract);
        return employContract;
    }

    /**
      * 功能：终止
      * @param request
     */
    public EmployContract repeal(SimpleRequest request) throws RuntimeException {
        EmployContract employContract = request.getO(EmployContract.class);
        employContract.setState("repeal");
        return employContractRepository.saveAndFlush(employContract);
    }


    /**
     * 功能：查询聘用合同
     * @param request
     * @return
     * @throws Exception
     */
    public Page<EmployContract> find(SimpleRequest request) throws Exception {
        List<Map> filters = request.get("condition");
        JSONObject djzt = new JSONObject();
        djzt.put("field","state");
        djzt.put("operator","NE");
        djzt.put("value","delete");
        filters.add(djzt);
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return employContractRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"),sort));
    }

    public EmployContract findOne(SimpleRequest request){
        EmployContract employContract = employContractRepository.findOne((String) request.get("id"));
        if(employContract == null){
            List<EmployContract> employContracts = employContractRepository.findAllById((String)request.get("id"));
            if(!employContracts.isEmpty()) {
                employContract = employContracts.stream().findFirst().get();
            }
        }
        return employContract;
    }

    public List<Map> findByEmployee(SimpleRequest request){
        List<EmployContract> employContracts = employContractRepository.findByEmployee(request.get("employeeId"));
//        EmployContract employContract;
//        if(!employContracts.isEmpty()){
//            employContract = employContracts.stream().findFirst().get();
//            return employContract;
//        }else {
//            return null;
//        }
        List<Map> maps = new ArrayList<>();
        if (!employContracts.isEmpty()){
            employContracts.forEach(employContract -> {
                String state = employContract.getState();
                maps.add(MapUtil.mapper(
                        "id",employContract.getId(),
                        "state",findState(state),
                        "createDate", DateUtil.format(employContract.getCreateDate(),DateUtil.SHOW_DATE_FORMAT)
                ));
            });
        }
        return maps;
    }
    public static String findState(String state){
        if("create".equals(state)){
            return "创建";
        }else if ("done".equals(state)){
            return "审核";
        }else if ("repeal".equals(state)){
            return "终止";
        }else {
            return "删除";
        }
    }
}
